const fs = require("fs");
const path = require("path");
const dir = path.resolve(__dirname, "..", "lib");

function switchVersion(version) {
  try {
    ["cjs", "es", "umd"].forEach((format) => {
      const src = path.join(dir, version, `inex.${format}.js`);
      const dest = path.join(dir, `inex.${format}.js`);
      const content = fs.readFileSync(src, "utf-8");
      try {
        fs.unlinkSync(dest);
      } catch (error) {}
      fs.writeFileSync(dest, content, "utf-8");
    });
    console.log(`[weightbill-designer] Switched to Vue ${version} mode`);
  } catch (error) {
    console.log(
      `[weightbill-designer] Failed to switch to Vue ${version} mode. Please try again with "npx weighbill-switch v${version}"`
    );
  }
}

function loadModule(name) {
  try {
    return require(name);
  } catch (e) {
    return undefined;
  }
}

module.exports.switchVersion = switchVersion;
module.exports.loadModule = loadModule;
